package com.bems.action;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;


import com.bems.common.UtilEnum;
import com.bems.jdbc.common.DBManager;
import com.bems.pojo.Group;
import com.bems.pojo.User;
import com.bems.service.UserSerive;
import com.bems.util.DigestMD;
import com.bems.util.PageUtil;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import com.oreilly.servlet.multipart.FilePart;
import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.ParamPart;
import com.oreilly.servlet.multipart.Part;

import cn.org.ape.BaseAction;

public class UserAction extends BaseAction 
{
	   private static final String EXIT = "../index.html";//退出
	   private static final String INDEX_USER = "../client/index.html";
	   private int id;
	   private User user;
	   private int type;//用户组
	   private int limit;
	    private int page;
	    private int isuser;//
			
			


			


			UserSerive userSerive = new UserSerive();
		
			
			public void info()
			{
				 User user=new User().get(id);
				 Gson gson = new Gson();
				 DBManager.closeConnection();
				 printJson(gson.toJson(user).toString());
			}
			
			public void user() 
			{
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("type", 2);
				Long group_id = new Group().get(map ).getId();
				List<User> list = userSerive.getUsersByGroup(group_id );
				Gson gson = new Gson();
				JsonElement element = gson.toJsonTree(list);
				
				DBManager.closeConnection();
				printJson(element.toString());
			}
	
	 		/**
	   		 * 登录
	   		 */
			public void login()
			{

				JsonObject jsonObject = new JsonObject();
				
				user=userSerive.verify(user.getAccount(), user.getPassword());
				if (user!=null&&user.getStatus()==UtilEnum.User_Status.IsUse.getValue())
				{
						if(user.Group().getType()==UtilEnum.Group_Type.Admin.getValue())//管理员登录
				    {
							session.setAttribute("user", user);	
				    jsonObject.addProperty("success", true);
				    
				    }else if(user.Group().getType()==UtilEnum.Group_Type.User.getValue())
				    		{
				    		session.setAttribute("user", user);	
				    			if(isuser==1)
				    			{
				    				DBManager.closeConnection();//释放链接
				    				printJson("{success:true}");
				    				
				    				 return;
				    			}
				    			DBManager.closeConnection();//释放链接
				    		
				    		sendRedirect(INDEX_USER);//重定向
				    		}
				}
				else {
					jsonObject.addProperty("success", false);
					jsonObject.addProperty("message", "登录失败");
				}
				DBManager.closeConnection();//释放链接
				printJson(jsonObject.toString());
			}
			
			
			public void exit() 
			{
				session.removeAttribute("user");
				sendRedirect("../index.html");
			}
			
			/**
			 * 用户表
			 */
			public void list() 
			{
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("type", type);
				Long group_id =new Group().get(map).getId();
				PageUtil pageutil = userSerive.getUsersByGroup(group_id , page, limit);
				JsonObject jsonObject = new JsonObject();
				jsonObject.addProperty("totalCount", pageutil.getTotalpage());
				Gson gson = new Gson();
				
				jsonObject.add("resultList", gson.toJsonTree(pageutil.getList()));
				DBManager.closeConnection();
				printJson(jsonObject.toString());
			}
			
			
			public void add()
			{
				
				Map<String, Object> map = new HashMap<String, Object>();
				try {
					//MultipartParser mp = new MultipartParser(request, 10*1024*1024);// 10MB
					MultipartParser mp =new MultipartParser(request, 10*1024*1024, true, true, "UTF-8");
					 Part part;
				      while ((part = mp.readNextPart()) != null) {
				        String name = part.getName();
				        if (part.isParam()) {
				          // it's a parameter part
				          ParamPart paramPart = (ParamPart) part;
				          String value = paramPart.getStringValue();
				         // System.out.println("param: name=" + name + "; value=" + value);
				          map.put(name, value);
				        }
				        else if (part.isFile()) {
				          // it's a file part
				          FilePart filePart = (FilePart) part;
				          String fileName = filePart.getFileName();
				          if (fileName != null) {
				            File dir=new File("sfrz.txt");
				            if(!dir.exists())
				            	dir.createNewFile();
							// the part actually contained a file
				             filePart.writeTo(dir);
				           
				           String authentication= FileUtils.readFileToString(dir);
				        	  map.put("authentication", authentication);
				          }
				          else { 
				            // the field did not contain a file
				            //out.println("file: name=" + name + "; EMPTY");
				          }
				         // out.flush();
				        }
				      }
				} catch (IOException e) {
	
					e.printStackTrace();
				} 
				User user = new User();
				 try {
					BeanUtils.populate(user, map);
					user.setCreatetime(new Timestamp(new Date().getTime()));
					Long r = userSerive.save(user);
					String json="";
					 DBManager.closeConnection();
						if(r==null)
						{
							 json ="{msg:'插入失败'}";
							//printJson(json);
							//return;
						}else if(r>0){
							 json ="{'msg':'成功'}";
							//printJson(json);
							//return;
						}else {
							 json ="{msg:'存在该帐号信息'}";
						
							//return;
						}
						//printJson(json);
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
					
			
				
			}
			
			
			public void update()
			{
				
				Map<String, Object> map = new HashMap<String, Object>();
				try {
					//MultipartParser mp = new MultipartParser(request, 10*1024*1024);// 10MB
					MultipartParser mp =new MultipartParser(request, 10*1024*1024, true, true, "UTF-8");
					 Part part;
				      while ((part = mp.readNextPart()) != null) {
				        String name = part.getName();
				        if (part.isParam()) {
				          // it's a parameter part
				          ParamPart paramPart = (ParamPart) part;
				          String value = paramPart.getStringValue();
				         // System.out.println("param: name=" + name + "; value=" + value);
				          
				          map.put(name, value);
				        }
				        else if (part.isFile()) {
				          // it's a file part
				          FilePart filePart = (FilePart) part;
				          String fileName = filePart.getFileName();
				          if (fileName != null) {
				            File dir=new File("sfrz.txt");
				            if(!dir.exists())
				            	dir.createNewFile();
							// the part actually contained a file
				             filePart.writeTo(dir);
				           
				           String authentication= FileUtils.readFileToString(dir);
				        	  map.put("authentication", authentication);
				          }
				          else { 
				            // the field did not contain a file
				            //out.println("file: name=" + name + "; EMPTY");
				          }
				         // out.flush();
				        }
				      }
				} catch (IOException e) {
	
					e.printStackTrace();
				} 
				//User user = new User();
				 
					//BeanUtils.populate(user, map);
				 if(map.get("status")==null)
				     map.put("status", 1);
					if(StringUtils.isEmpty(map.get("password").toString()))
					{
						 map.remove("password");
					}else {
						map.put("password", DigestMD.MD5(map.get("password").toString()));
					}
					int r =	new User().update(map,Long.parseLong(map.get("id").toString()) );

				String json="";
				 DBManager.closeConnection();
					 if(r>0){
						json ="{'msg':'成功'}";
						//printJson(json);
						//return;
					}else {
						 json ="{msg:'失败'}";
						
						//return;
					}
					 //printJson(json);
			}
			
			public void delete()
			{
				boolean r = new User().delete(id);
				String json="";
				if (r) 
				{
					 json="{'msg':'删除成功'}";
					 
				}else {
					json="{'msg':'删除失败'}";
				}
				printJson(json);
			
			}

			
			
			/**
			 * 下面都是get和set方法
			 * 
			 */
			public int getId() {
				return id;
			}


			public void setId(int id) {
				this.id = id;
			}


			public User getUser() {
				return user;
			}


			public void setUser(User user) {
				this.user = user;
			}


			public int getType() {
				return type;
			}


			public void setType(int type) {
				this.type = type;
			}

			public int getPage() {
				return page;
			}


			public void setPage(int page) {
				this.page = page;
			}


			public void setLimit(int limit) {
				this.limit = limit;
			}
			public int getLimit() {
				return limit;
			}

			public int getIsuser() {
				return isuser;
			}

			public void setIsuser(int isuser) {
				this.isuser = isuser;
			}


		
}
